package org.jeecg.modules.gudingzichan.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.activiti.engine.IdentityService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.repository.Model;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.JsonUtils;
import org.jeecg.modules.gudingzichan.entity.Gudingzichan;
import org.jeecg.modules.gudingzichan.mapper.GudingzichanMapper;
import org.jeecg.modules.gudingzichan.service.IGudingzichanService;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.util.CollectionUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Description: gudingzichan
 * @Author: jeecg-boot
 * @Date:   2020-07-31
 * @Version: V1.0
 */
@Service
public class GudingzichanServiceImpl extends ServiceImpl<GudingzichanMapper, Gudingzichan> implements IGudingzichanService {

    @Autowired
    private GudingzichanMapper gudingzichanMapper;

    @Autowired
    private IdentityService identityservice;
    @Autowired
    private RuntimeService runtimeservice;
    @Autowired
    private TaskService taskService;
    @Autowired
    private RepositoryService repositoryService;
    @Autowired
    private ISysUserService userService;

    @Override
    public void handleStatus(org.jeecg.modules.gudingzichan.entity.Gudingzichan gdzc) {
//        org.jeecg.modules.gudingzichan.entity.Gudingzichan gdzc = new org.jeecg.modules.gudingzichan.entity.Gudingzichan();
        gdzc.setTaskId("");
        gdzc.setProcessInstanceId("");
//        gdzc.setZichanStatus(gudingzichan.getZichanStatus());
//        gdzc.setTiaojiDeptId(gudingzichan.getTiaojiDeptId());
//        gdzc.setWaijieDeptId(gudingzichan.getWaijieDeptId());
//        gdzc.setJuanzengDanwei(gudingzichan.getJuanzengDanwei());
//        gdzc.setId(gudingzichan.getId());
        String ids=gdzc.getId();
        String[] idStr=ids.split(",");
        for (int i=0;i<idStr.length;i++){
            gdzc.setId(idStr[i]);
            this.baseMapper.updateById(gdzc);
            LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            this.startFlow(gdzc,user);
        }

    }

    @Override
    public void handleTjYjStatus(org.jeecg.modules.gudingzichan.entity.Gudingzichan gdzc) {
//        org.jeecg.modules.gudingzichan.entity.Gudingzichan gdzc = new org.jeecg.modules.gudingzichan.entity.Gudingzichan();
        gdzc.setTaskId("");
        gdzc.setProcessInstanceId("");
//        gdzc.setZichanStatus(gudingzichan.getZichanStatus());
//        gdzc.setTiaojiDeptId(gudingzichan.getTiaojiDeptId());
//        gdzc.setWaijieDeptId(gudingzichan.getWaijieDeptId());
//        gdzc.setJuanzengDanwei(gudingzichan.getJuanzengDanwei());
//        gdzc.setId(gudingzichan.getId());
        String ids=gdzc.getId();
        String[] idStr=ids.split(",");
        for (int i=0;i<idStr.length;i++){
            gdzc.setId(idStr[i]);
            this.baseMapper.updateById(gdzc);
            LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            this.startTjYjFlow(gdzc,user);
        }

    }

    @Override
    public void startFlow(org.jeecg.modules.gudingzichan.entity.Gudingzichan gudingzichan, LoginUser user) {
        List<SysUser> userList = userService.queryByPost(user.getOrgCode(),"shenpiren");
        if(CollectionUtils.isEmpty(userList)){
            throw new RuntimeException("部门负责人为空");
        }

        String businesskey = "" + gudingzichan.getId();

        identityservice.setAuthenticatedUserId(user.getUsername());

        Map<String, Object> variables = new HashMap<String, Object>();
        variables.put("applyUser", user.getUsername());
        variables.put("auditUser",userList.get(0).getUsername());
        variables.put("status",gudingzichan.getStatus());
        variables.put("zicje",gudingzichan.getJine());
        variables.put("sqlx",gudingzichan.getSqlx());
        Model modelData = null;
//        if(gudingzichan.getZichanStatus().equalsIgnoreCase("5")){
//            modelData = repositoryService.getModel("842540");
//        }else {
//            modelData = repositoryService.getModel(gudingzichan.getBmjb());
//        }
        modelData = repositoryService.getModel(gudingzichan.getBmjb());
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().deploymentId(modelData.getDeploymentId()).singleResult();

        ProcessInstance instance=runtimeservice.startProcessInstanceById(processDefinition.getId(),businesskey,variables);
        String instanceid=instance.getId();
        gudingzichan.setProcessInstanceId(instanceid);
        Task task = taskService.createTaskQuery().processInstanceId(instance.getId()).taskAssignee(user.getUsername()).singleResult();
        gudingzichan.setTaskId(task.getId());
        this.baseMapper.updateById(gudingzichan);
        taskService.complete(task.getId(),variables);
    }

    @Override
    public void startTjYjFlow(org.jeecg.modules.gudingzichan.entity.Gudingzichan gudingzichan, LoginUser user) {
        List<SysUser> userList = userService.queryByPost(user.getOrgCode(),"shenpiren");
        if(CollectionUtils.isEmpty(userList)){
            throw new RuntimeException("部门负责人为空");
        }

        String businesskey = "" + gudingzichan.getId();

        identityservice.setAuthenticatedUserId(user.getUsername());

        Map<String, Object> variables = new HashMap<String, Object>();
        variables.put("applyUser", user.getUsername());
        variables.put("auditUser",userList.get(0).getUsername());
//        variables.put("status",gudingzichan.getStatus());
//        variables.put("zicje",gudingzichan.getJine());
//        variables.put("sqlx",gudingzichan.getSqlx());
        Model modelData = null;
//        if(gudingzichan.getZichanStatus().equalsIgnoreCase("5")){
//            modelData = repositoryService.getModel("842540");
//        }else {
//            modelData = repositoryService.getModel(gudingzichan.getBmjb());
//        }
        modelData = repositoryService.getModel("2345001");
        ProcessDefinition processDefinition = repositoryService.createProcessDefinitionQuery().deploymentId(modelData.getDeploymentId()).singleResult();

        ProcessInstance instance=runtimeservice.startProcessInstanceById(processDefinition.getId(),businesskey,variables);
        String instanceid=instance.getId();
        gudingzichan.setProcessInstanceId(instanceid);
        Task task = taskService.createTaskQuery().processInstanceId(instance.getId()).taskAssignee(user.getUsername()).singleResult();
        gudingzichan.setTaskId(task.getId());
        this.baseMapper.updateById(gudingzichan);
        taskService.complete(task.getId(),variables);
    }

    @Override
    public void complateTask(LoginUser loginUser, String taskId,String processInstanceId, Integer status, String memo, String auditUser, Float zicje,String sqlx) {
//        taskService.claim(taskId,loginUser.getId());
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();

        if(StringUtils.isBlank(memo)){
            memo = status == 1?"通过":"驳回";
        }

        Map map = new HashMap(){{
            put("zicje", zicje);
            put("status", status);
            put("sqlx",sqlx);

            if(auditUser != null) {
                put("auditUser", auditUser);
                runtimeservice.setVariable(task.getExecutionId(),"auditUser",auditUser);
            }
        }};
        map.put("memo",memo);

        taskService.addComment(taskId, processInstanceId, JsonUtils.toJsonString(map));
        taskService.complete(taskId, map);
    }

    @Override
    public void complateTjYjTask(LoginUser loginUser, String taskId, String processInstanceId, Integer status, String memo, String auditUser) {
        Task task = taskService.createTaskQuery().taskId(taskId).singleResult();

        if(StringUtils.isBlank(memo)){
            memo = status == 1?"通过":"驳回";
        }

        Map map = new HashMap(){{
            put("status", status);

            if(auditUser != null) {
                put("auditUser", auditUser);
                runtimeservice.setVariable(task.getExecutionId(),"auditUser",auditUser);
            }
        }};
        map.put("memo",memo);

        taskService.addComment(taskId, processInstanceId, JsonUtils.toJsonString(map));
        taskService.complete(taskId, map);
    }

    @Override
    public void applyAgain(Gudingzichan gudingzichan, LoginUser user) {

        Task task = taskService.createTaskQuery().processInstanceId(gudingzichan.getProcessInstanceId()).taskAssignee(user.getUsername()).singleResult();
        gudingzichan.setTaskId(task.getId());
        this.baseMapper.updateById(gudingzichan);
        Map<String, Object> variables = new HashMap<String, Object>();
        variables.put("status",null);
        taskService.complete(task.getId(),variables);
    }
    @Override
    public List<org.jeecg.modules.gudingzichan.entity.Gudingzichan> myApplyListTest( LoginUser user, org.jeecg.modules.gudingzichan.entity.Gudingzichan gudingzichan) {
        return this.baseMapper.myApplyListTest(user,gudingzichan);
    }

    @Override
    public IPage<org.jeecg.modules.gudingzichan.entity.Gudingzichan> myApplyList(Page<org.jeecg.modules.gudingzichan.entity.Gudingzichan> page, LoginUser user, org.jeecg.modules.gudingzichan.entity.Gudingzichan gudingzichan) {
        return this.baseMapper.myApplyList(page,user,gudingzichan);
    }

    @Override
    public List<Gudingzichan> myApplyList2( LoginUser user,Gudingzichan gudingzichan) {
        return this.baseMapper.myApplyList2(user,gudingzichan);
    }

    @Override
    public IPage<org.jeecg.modules.gudingzichan.entity.Gudingzichan> myTodoTasks(Page<org.jeecg.modules.gudingzichan.entity.Gudingzichan> page, LoginUser user, org.jeecg.modules.gudingzichan.entity.Gudingzichan gudingzichan) {
        return this.baseMapper.myTodoTasks(page,user,gudingzichan);
    }
    @Override
    public IPage<org.jeecg.modules.gudingzichan.entity.Gudingzichan> myTodoTasks2(Page<org.jeecg.modules.gudingzichan.entity.Gudingzichan> page, LoginUser user, org.jeecg.modules.gudingzichan.entity.Gudingzichan gudingzichan) {
        return this.baseMapper.myTodoTasks(page,user,gudingzichan);
    }
    @Override
    public IPage<org.jeecg.modules.gudingzichan.entity.Gudingzichan> myDoneTasks(Page<org.jeecg.modules.gudingzichan.entity.Gudingzichan> page, LoginUser user, org.jeecg.modules.gudingzichan.entity.Gudingzichan gudingzichan) {
        return this.baseMapper.myDoneTasks(page,user,gudingzichan);
    }
    @Override
    public IPage<org.jeecg.modules.gudingzichan.entity.Gudingzichan> myDoneTasks2(Page<org.jeecg.modules.gudingzichan.entity.Gudingzichan> page, LoginUser user, org.jeecg.modules.gudingzichan.entity.Gudingzichan gudingzichan) {
        return this.baseMapper.myDoneTasks(page,user,gudingzichan);
    }
    @Override
    public IPage<org.jeecg.modules.gudingzichan.entity.Gudingzichan> pageList(Page<org.jeecg.modules.gudingzichan.entity.Gudingzichan> page, org.jeecg.modules.gudingzichan.entity.Gudingzichan gudingzichan) {
        return this.baseMapper.pageList(page,gudingzichan);
    }

}
